package com.lagou.module4_6;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

/**
 * @author wsl
 * @date 2021/8/1 18:21
 * @project_name javase
 */
public class Client {//客户端

    public static void main(String[] args) {
        Socket sk = null;
        Scanner sc= null;
        PrintStream ps = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            //1.创建Socket类型的对象并提供服务器的主机名和端口号
            sk = new Socket("127.0.0.1",8888);
            System.out.println("服务器连接成功！");

            //2.使用输入输出流进行通信
             sc = new Scanner(System.in);
             ps = new PrintStream(sk.getOutputStream());
             br = new BufferedReader(new InputStreamReader(sk.getInputStream()));

            while (true) {
                //实现客户端发送的内容由用户从键盘输入
                System.out.println("请输入您要发送的内容：");
                String str = sc.next();
                //客户端用户发消息给服务端
                ps.println(str);
                //当发送的数据内容是"end",则聊天结束！
                if ("end".equalsIgnoreCase(str)) {
                    System.out.println("聊天结束！");
                    break;
                }
                //实现接收服务器发来的字符串内容
                String str2 = br.readLine();
                System.out.println("服务器回发的消息是："+str2);

                //4.将所有已输入的字符串按字典顺序倒序录入到项目下abc.txt中
                File file = new File("");
                String absolutePath = file.getAbsolutePath();
                bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""+absolutePath+"/abc.txt")));
                //把字符串转换成字符数组
                char[] cArr = str.toCharArray();
                //把字符数组进行字典排序
                Arrays.sort(cArr);
                //用for循环对字符数组倒叙输出
                for (int i=0; i<cArr.length-1; i++){
                    bw.write(cArr[cArr.length-1-i]);
                }
                System.out.println("写入数据成功！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭Socket并释放相关的资源
            if (null != bw){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ps){
                ps.close();
            }
            if (null != sc){
                sc.close();
            }
            if (null != sk){
                try {
                    sk.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
